<?php

namespace control;

class liquidAmmoniaClass extends adIndexClass
{

    private const page = 'liquidAmmonia'; # 权限
    private const table = 'liquid_ammonia'; # 数据表
    private const title = '液氨液位';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'liquid_level'         => [
                'name'  => '液位',
                'width' => 200,
            ],
            'volume'         => [
                'name'  => '体积',
                'width' => 200,
            ],
            'weight'          => [
                'name'  => '重量',
                'width' => 200,
            ],
            'time'          => [
                'name'  => '日期',
                'width' => 150,
            ],
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '液位'   => text(array("name" => "liquid_level")),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*钢瓶收发明细入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*钢瓶收发明细列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'liquid_level' => $this->post('liquid_level'),
            'coid'=>self::$coid,
            'type'=>1,
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate) . hidden(["name" => "cylinderId", "value" => $array['id']]);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] .clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $title = ['液位', '体积','重量'];
            $data[] = [];
            $text = $this->control['name'] . "下载了液氨液位导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '液氨液位导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * Excel导入
     */
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $field = array(
                        "id" => self::getId(),
                        'coid' => self::$coid,
                        'liquid_level' => $cell['液位'],
                        'volume' => $cell['体积'],
                        'weight' => $cell['重量'],
                        'time' => $this->time,
                        'type' => 1,
                        'updateTime' => $this->time,
                    );

                    $annotation = [
                        'liquid_level' => '液位',
                        'weight' => '重量',
                        'volume' => '体积',
                    ];
                    $rules = [
                        'liquid_level' => 'required',
                        'weight' => 'required',
                        'volume' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    }else {
                        $warn = static::insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败，编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'液位',
                    'aliasName'=>'液位',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'重量',
                    'aliasName'=>'重量',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'体积',
                    'aliasName'=>'体积',
                    'isMust'=>false,
                ],
            ]
        };
    }
}